import { useEffect } from "react";
import { useLocation, useNavigate } from "react-router-dom";

export function Guard({ element, onRouterBefore }) {
  const location = useLocation();
  const navigate = useNavigate();
  const { pathname } = location;

  useEffect(() => {
    const nextPath = onRouterBefore(location);
    if (nextPath && nextPath !== pathname) {
      navigate(nextPath, { replace: true });
    }
  }, [location, navigate, pathname, onRouterBefore]);

  return element;
}
